from flask import Flask, render_template, request, jsonify,make_response
from flask_sqlalchemy import SQLAlchemy
import logging
import pymysql
import time
import random
import chardet
import os
import hashlib
from flask import session
import re
import datetime


app = Flask(__name__)
# 日志系统配置
handler = logging.FileHandler('log/app.log', encoding='UTF-8')
# 设置日志文件，和字符编码
logging_format = logging.Formatter('%(levelname)s %(filename)s %(lineno)d %(message)s')
# 将日志记录器指定日志的格式
handler.setFormatter(logging_format)
# 添加日志设置
app.logger.addHandler(handler)
# 设置SQLALCHEMY连接数据库信息
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://yang:Yy123456@yang-sql.mysql.rds.aliyuncs.com:13306/mydata?charset=utf8'
app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)
db = SQLAlchemy(app)
# 生成session的秘钥
app.config["SECRET_KEY"] = os.urandom(24)
# 设置session时长
PERMANENT_SESSION_LIFETIME = datetime.timedelta(hours=1)

# 映射用户表
class userTable(db.Model):
    __tablename__ = 'Users'
    userName = db.Column(db.String(255), primary_key=True)
    passWord = db.Column(db.String(255))
    tableName = db.Column(db.String(255))

# 登录页
@app.route("/")
@app.route("/login")
def login():
    return render_template("login.html")

# 验证账号密码或者session信息
@app.route("/yanzheng",methods=['POST', 'GET'])
def yanzheng():
    if request.method == 'POST':
        if len(str(request.form.get("username"))) != 0 and len(str(request.form.get("password"))) != 0:
            username = request.form.get("username")
            password = hashlib.md5(str(request.form.get("password")).encode()).hexdigest()
            connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306,database="mydata")
            cursor = connect.cursor()
            isExitst = "SELECT * FROM users where userName = '{}' and passWord = '{}';".format(username, password)
            count = cursor.execute(isExitst)
            # 账号密码正确 跳转页面
            if count == 1:
                tableName = cursor.fetchone()[2]
                # 查找是否有上次的数据
                try:
                    selectSql = "SELECT * FROM {} limit 3".format(tableName)
                    cursor.execute(selectSql)
                except Exception:
                    session['tableName'] = tableName
                    session['userName'] = username
                    session['passWord'] = password
                    print("查找表数据发现异常")
                    logging.info(Exception)
                    return render_template("index.html")
                else:
                    result = list(cursor.fetchall())
                    session['tableName'] = tableName
                    session['userName'] = username
                    session['passWord'] = password
                    title = "缓存数据预览"
                    cursor.close()
                    connect.close()
                    return render_template("index.html", data=result, title=title)
            else:
                cursor.close()
                connect.close()
                return render_template("login.html", error="账号或密码错误")
        else:
            return render_template("login.html", error="账号或密码错误")
    if request.method == 'GET':
        username = session.get("userName")
        password = session.get("passWord")
        connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306,database="mydata")
        cursor = connect.cursor()
        isExitst = "SELECT * FROM users where userName = '{}' and passWord = '{}';".format(username, password)
        count = cursor.execute(isExitst)
        # 账号密码正确 跳转页面
        if count == 1:
            tableName = cursor.fetchone()[2]
            # 查找是否有上次的数据
            selectSql = "SELECT * FROM {} limit 3".format(tableName)
            cursor.execute(selectSql)
            result = list(cursor.fetchall())
            session['tableName'] = tableName
            title = "缓存数据预览"
            cursor.close()
            connect.close()
            return render_template("index.html", data=result, title=title)
        else:
            return render_template("login.html", error="会话已失效")


# 注册账号
@app.route("/zhuce", methods=['POST'])
def zhuce():
    if request.method == 'POST':
        username = str(request.form.get("username"))
        # 加密md5加密
        password = hashlib.md5(str(request.form.get("password")).encode()).hexdigest()
        connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306, database="mydata")
        # 判断账号表中的数据是否小于30
        cursor = connect.cursor()
        result = cursor.execute("SELECT userName FROM users;")
        isUserName = cursor.execute("SELECT userName FROM `users` where userName = '{}';".format(username))
        # 判断账号表中的数据是否小于30
        if isUserName != 0:
            return jsonify({"isCreate": "isUserName"})
        if result <= 30 and isUserName == 0:
            tableName = ""
            for i in range(5):
                tableName += chr(random.randint(97, 122))
            tableName += str(time.time())[3:8]
            insertSql = """
                        insert into `users` (userName,passWord,tableName) values
                        (%s,%s,%s)
                        """
            cursor.execute(insertSql, (username, password, tableName))
            connect.commit()
            cursor.close()
            connect.close()
            print("账号创建成功!")
            return jsonify({"isCreate": "success"})
        else:
            cursor.close()
            connect.close()
            print("账号创建失败!")
            return jsonify({"isCreate": "failed"})
    return render_template("test.html")

# 登录后上传数据
@app.route("/upload", methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        encodeType = chardet.detect(file.read()).get("encoding")
        file.seek(0)
        lines = file.readlines()
        # 拿第一行
        ondline = lines[0].decode(encodeType)
        # 判断是否有\t
        tab = re.compile("\t")
        length = len(re.findall(tab, ondline))
        data = []
        viewData = []
        count = 0
        try:
            if length > 0:
                # 用\t对文本进行分割
                for line in lines:
                    temp = []
                    for i in str(line.decode(encodeType)).split("\t"):
                        items = re.findall(r'"(.*?)"', str(i))
                        if len(items) > 0:
                            temp.append(items[0])
                        else:
                            temp.append(str(i))
                    data.append(temp)
                    count += 1
                    if count < 3:
                        viewData.append(temp)
            else:
                # 用","对文本进行分割
                for line in lines:
                    temp = []
                    for i in str(line.decode(encodeType)).split(","):
                        items = re.findall(r'"(.*?)"', str(i))
                        if len(items) > 0:
                            temp.append(items[0])
                        else:
                            temp.append(str(i))
                    data.append(temp)
                    count += 1
                    if count < 3:
                        viewData.append(temp)
        except Exception :
            return jsonify({"data": "数据有异常"})
        else:
            # 判断该用户数据表是否存在,存在即删除
            tableName = session.get("tableName")
            connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306, database="mydata")
            cursor = connect.cursor()
            cursor.execute("drop table if exists `{}`".format(tableName))
            # 创建该表格
            createSql = "create table `{}` (".format(tableName)
            for i in range(len(viewData[0])):
                if i != len(viewData[0])-1:
                    createSql += "c" + str(i + 1) + " varchar(255),"
                else:
                    createSql += "c" + str(i + 1) + " varchar(255)"
            createSql += ")ENGINE=InnoDB DEFAULT CHARSET=utf8;"
            cursor.execute(createSql)

            # 将数据写进该表格
            insetSql = "insert into {} (".format(tableName)
            for i in range(len(viewData[0])):
                if i != len(viewData[0])-1:
                    insetSql += "c" + str(i+1)+","
                else:
                    insetSql += "c" + str(i + 1)
            insetSql += ") values("
            for i in range(len(viewData[0])):
                if i != len(viewData[0]) - 1:
                    insetSql += "%s,"
                else:
                    insetSql += "%s"
            insetSql += ");"
            # 多条语句进行插入
            cursor.executemany(insetSql, tuple(data))
            # 提交
            connect.commit()
            cursor.close()
            connect.close()
            return jsonify({"data": viewData})
            # return render_template("index.html", data=data)

# isData 跳转到操作界面 将数据写入该用户的数据库 后进行可视化前操作
@app.route("/isData")
def isData():
    username = session.get("userName")
    password = session.get("passWord")
    connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306,
                              database="mydata")
    cursor = connect.cursor()
    isExitst = "SELECT * FROM users where userName = '{}' and passWord = '{}';".format(username, password)
    count = cursor.execute(isExitst)
    # 账号密码正确 跳转页面
    if count == 1:
        return render_template("inieEcharts.html")
    else:
        return render_template("login.html", error="请登录后再访问")

# 判断sql语句包不包含敏感词
def judgeSQL(sql):
    isDrop = False
    dropPatt = re.compile(r'drop', re.I)
    truncatePatt = re.compile(r'TruncatePatt', re.I)
    deletePatt = re.compile(r'delete', re.I)
    # 忽略大小写匹配sql语句中的敏感词
    if len(re.findall(dropPatt, sql)) > 0 or len(re.findall(truncatePatt, sql)) > 0 or len(re.findall(deletePatt, sql)) > 0:
        isDrop = True
    return isDrop

# 执行sql语句
@app.route("/sqlExecute", methods=['POST'])
def sqlExecute():
    if request.method == 'POST':
        oldSql = request.form.get("sql")
        # 判断sql语句中是否有敏感词
        if judgeSQL(oldSql) == False:
            newSql = str(oldSql).replace("myTable", session.get("tableName"))
            connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306,database="mydata")
            cursor = connect.cursor()
            try:
                cursor.execute(newSql)
            except Exception:
                logging.info(newSql)
                logging.info(Exception)
                result = ["你输入的SQL语句有语法错误"]
                tempList = ["你输入的SQL语句有语法错误"]
            else:
                tempList = cursor.fetchall()
                tempDict = {}
                result = []
                for index in range(len(tempList[0])):
                    tempDict[index] = []
                for row in tempList:
                    for index in range(len(row)):
                        tempDict[index].append(row[index])
                for key in tempDict:
                    result.append(tempDict[key])
            finally:
                cursor.close()
                connect.close()
        else:
            result = ["你输入的SQL语句敏感词"]
            tempList = ["你输入的SQL语句敏感词"]
        return jsonify({"resultVer": tempList, "resultHor": result})


# 返回改表部分数据
def returnData():
    # 显示部分数据
    connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306,
                              database="mydata")
    cursor = connect.cursor()
    selectSql = "select * from {} limit 100;".format(session.get("tableName"))
    cursor.execute(selectSql)
    data = list(cursor.fetchall())
    temp = []
    for i in range(len(data[0])):
        temp.append("c" + str(i + 1))
    data.insert(0, temp)
    cursor.close()
    connect.close()
    return data

# 初始化line图
@app.route("/line", methods=['POST', "GET"])
def line():
    if request.method == 'POST':
        session["title"] = request.form.get("lineTitle")
        session["subtitle"] = request.form.get("lineSubtitle")
        session["stack"] = request.form.get("lineStack")
        session["smooth"] = request.form.get("lineSmooth")
        session["areaStyle"] = request.form.get("lineAreaStyle")
        session["label"] = request.form.get("lineLabel")
        session["trigger"] = request.form.get("lineTrigger")
        # 显示部分数据
        connect = pymysql.connect(host="yang-sql.mysql.rds.aliyuncs.com", user="yang", passwd="Yy123456", port=13306,database="mydata")
        cursor = connect.cursor()
        selectSql = "select * from {} limit 100;".format(session.get("tableName"))
        cursor.execute(selectSql)
        data = list(cursor.fetchall())
        temp = []
        for i in range(len(data[0])):
            temp.append("c"+str(i+1))
        data.insert(0, temp)
        cursor.close()
        connect.close()
        return render_template("lineE.html", data=returnData())
    elif request.method == 'GET' and len(session) > 0 and len(session.get("tableName")) > 0:
        return render_template("lineE.html", data=returnData())
    else:
        return render_template("login.html", error="会话已失效")

# 返回line图
@app.route("/viewLine", methods=['POST'])
def viewLine():
    if request.method == 'POST':
        data = request.form.get("data")
        rowList = str(data).split("\r\n")
        dataDict = dict()
        xData = []
        for row in rowList:
            temp = str(row).split("\t")
            if temp[0] == "类目":
                for index in range(1, len(temp)):
                    xData.append(temp[index])
            else:
                dataDict[temp[0]] = []
                for index in range(1, len(temp)):
                    dataDict[temp[0]].append(temp[index])
        title = session.get("title")
        subtitle = session.get("subtitle")

        if session.get("trigger") == "true":
            trigger = "axis"
        else:
            trigger = ""
        series = ""
        legend = []
        for key in dataDict:
            legend.append(key)
            # 名字
            series += "{name:'%s', type: 'line',"%(str(key))
            if session.get("stack") == "true":
                series += "stack: '总量',"
            if session.get("areaStyle") == "true":
                series += "areaStyle: {},"
            if session.get("smooth") == "true":
                series += "smooth: true,"
            if session.get("label") ==  "true":
                series += "label: {show: true,position: 'top'},"
            series += "emphasis: {focus: 'series'},"
            series += "data:["
            for item in dataDict[key]:
                series += '"'+str(item)+'",'
            series += "]},"
        return render_template("line.html", xData=xData, title=title, subtitle=subtitle, trigger=trigger, series=series,legend=legend)

# 初始化scatter图
@app.route("/scatter", methods=['POST', "GET"])
def scatter():
    if request.method == 'POST':
        session["title"] = request.form.get("scaTitle")
        session["subtitle"] = request.form.get("scaSubtitle")
        session["scaX"] = request.form.get("scaX")
        session["scaY"] = request.form.get("scaY")
        session["scaTrigger"] = request.form.get("scaTrigger")
        session["scaBorder"] = request.form.get("scaBorder")
        session["scaAvg"] = request.form.get("scaAvg")
        session["scaMM"] = request.form.get("scaMM")
        return render_template("scatterE.html", data=returnData())
    elif request.method == 'GET' and len(session) > 0 and len(session.get("tableName")) > 0:
        return render_template("scatterE.html", data=returnData())
    else:
        return render_template("login.html", error="会话已失效")



# 返回Scatter图
@app.route("/viewScatter", methods=['POST'])
def viewScatter():
    if request.method == 'POST':
        data = request.form.get("data")
        if data != "":
            dataList = str(data).split("\r\n")
            names = []
            xData = []
            yData = []
            for index in range(len(dataList)):
                # 第一行
                if (index + 3) % 3 == 0:
                    names.append(dataList[index])
                # 第二行
                if (index + 2) % 3 == 0:
                    xData.append(list(map(float, dataList[index].split("    "))))
                # 第三行
                if (index + 1) % 3 == 0:
                    yData.append(list(map(float, dataList[index].split("    "))))
            dataDict = []

            for index in range(len(names)):
                zipList = list(map(list, zip(xData[index], yData[index])))
                tempDict = dict()
                tempDict['name'] = names[index]
                tempDict['type'] = 'scatter'
                tempDict['emphasis'] = {'focus': 'series'}
                tempDict['data'] = zipList
                if session.get('scaBorder') == 'true':
                    tempDict['markArea'] = {'silent': 'true', 'itemStyle': {'color': 'transparent', 'borderWidth': '1', 'borderType': 'dashed'}, 'data': [[{'name': names[index], 'xAxis': 'min', 'yAxis': 'min'}, {'xAxis': 'max', 'yAxis': 'max'}]]}
                if session.get('scaAvg') == 'true':
                    tempDict['markLine'] = {'lineStyle': {'type': 'solid'}, 'data': [{'type': 'average', 'name': '平均值'}, {'xAxis': int(sum(xData[index])/len(xData[index]))}]}
                if session.get('scaMM') == 'true':
                    tempDict['markPoint'] = {'data': [{'type': 'max', 'name': 'Max'},{'type': 'min', 'name': 'Min'}]}
                dataDict.append(tempDict)
            # 是否显示数据
            if session.get('scaTrigger') == 'true':
                Tooltip = """{
                            showDelay: 0,
                            formatter: function (params) {
                                if (params.value.length > 1) {
                                    return params.seriesName + ' :<br/>'
                                    + params.value[0] + '%s '
                                    + params.value[1] + '%s ';
                                }
                                else {
                                    return params.seriesName + ' :<br/>'
                                    + params.name + ' : '
                                    + params.value + '%s ';
                                }
                            },
                            axisPointer: {
                                show: true,
                                type: 'cross',
                                lineStyle: {
                                    type: 'dashed',
                                    width: 1
                                }
                            }}
                            """%(session.get("scaX"), session.get("scaY"), session.get("scaY"))
            else:
                Tooltip = "{}"
            return render_template('scatter.html', series=dataDict, scaY=session.get("scaY"), scaX=session.get("scaX"), legend=names, tooltip=Tooltip, title=session.get("title"), sTitle=session.get("subtitle"))


# 初始化pie图
@app.route('/pie', methods=['POST', 'GET'])
def pie():
    if request.method == 'POST':
        session["title"] = request.form.get("pieTitle")
        session["subtitle"] = request.form.get("pieSubtitle")
        session["pieRadius"] = request.form.get("pieRadius")
        session["pieSimple"] = request.form.get("pieSimple")
        session["pieCenter"] = request.form.get("pieCenter")
        session["pieLegend"] = request.form.get("pieLegend")
        session["pieTrigger"] = request.form.get("pieTrigger")
        return render_template("pieE.html", data=returnData())
    elif request.method == 'GET' and len(session) > 0 and len(session.get("tableName")) > 0:
        return render_template("pieE.html", data=returnData())
    else:
        return render_template("login.html", error="会话已失效")

# 返回pie图
@app.route("/viewPie", methods=['POST'])
def viewPie():
    if request.method == 'POST':
        data = request.form.get("data")
        if data != "":
            series = "{type: 'pie',data:["
            for row in str(data).split('\r\n'):
                series += "{name: '"
                series += row.split('	')[0]
                series += "',value: "
                series += str(float(row.split("	")[1]))
                series += "},"
            series += "],"
            # 是否为玫瑰图
            if session.get("pieSimple") == 'true':
                series += "roseType: 'area',"
            center = ""
            # 中间显示标签
            if session.get('pieCenter') == "true":
                series += "itemStyle: {borderRadius: 10,borderColor: '#fff',borderWidth: 2},label: {show: false,position: 'center'},emphasis: {label: {show: true,fontSize: '40',fontWeight: 'bold'}},labelLine: {show: false},"
            # 标签是否指向数据 不指向的时候 默认指向
            elif session.get("pieLegend") == 'false':
                series += "label: {show: false},emphasis: {label: {show: true}},"
            # 环形
            if session.get('pieRadius') == 'true':
                series += "radius:[150, 250]}"
            else:
                series += "radius:'50%'}"
            # 触控显示数据
            if session.get('pieTrigger') == 'true':
                trigger = "tooltip: {trigger: 'item'},"
            else:
                trigger = ""
            return render_template("pie.html", series=series, trigger=trigger, title=session.get('title'), subTitle=session.get('subtitle'), center=center)


# 初始化bar图
@app.route("/bar", methods=['POST', "GET"])
def bar():
    if request.method == 'POST':
        session["title"] = request.form.get("barTitle")
        session["subtitle"] = request.form.get("barSubtitle")
        session["barStack"] = request.form.get("barStack")
        session["horORVer"] = request.form.get("horORVer")
        session["showData"] = request.form.get("showData")
        session["avg"] = request.form.get("avg")
        session["trigger"] = request.form.get("barTrigger")
        return render_template("barE.html", data=returnData())
    elif request.method == 'GET' and len(session) > 0 and len(session.get("tableName")) > 0:
        return render_template("barE.html", data=returnData())
    else:
        return render_template("login.html", error="会话已失效")

# 返回bar图
@app.route("/viewBar", methods=['POST'])
def viewBar():
    if request.method == 'POST':
        data = request.form.get("data")
        rowList = str(data).split("\r\n")
        dataDict = dict()
        xAxis = ""
        yAxis = ""
        if session.get("horORVer") == "false":
            xAxis += " type: 'category',data: ["
        else:
            yAxis += " type: 'category',data: ["

        for row in rowList:
            temp = str(row).split("\t")
            if temp[0] == "类目":
                for index in range(1, len(temp)):
                    if session.get("horORVer") == "false":
                        xAxis += "'" + temp[index] + "',"
                    else:
                        yAxis += "'" + temp[index] + "',"
            else:
                dataDict[temp[0]] = []
                for index in range(1, len(temp)):
                    dataDict[temp[0]].append(temp[index])
        if session.get("horORVer") == "false":
            xAxis += "]"
        else:
            yAxis += "]"
        title = session.get("title")
        subtitle = session.get("subtitle")

        if session.get("trigger") == "true":
            trigger = "trigger: 'axis',axisPointer: {type: 'shadow'}"
        else:
            trigger = ""
        series = ""
        legend = []
        for key in dataDict:
            # 名字
            legend.append(key)
            series += "{name:'%s', type: 'bar',"%(str(key))
            if session.get("barStack") == "true":
                series += "stack: '总量',"
            if session.get("showData") == "true":
                series += " label: {show: true,position: 'top'},"
            if session.get("avg") == "true":
                series += " markLine: {data: [{type: 'average', name: '平均值'}]},"
            series += "markPoint: {data: [{type: 'max', name: '最大值'},{type: 'min', name: '最小值'}]},"
            series += " emphasis: {focus: 'series'},"
            series += "data:["
            for item in dataDict[key]:
                series += '"'+str(item)+'",'
            series += "]},"

        return render_template("bar.html", legend=legend, title=title, subtitle=subtitle, trigger=trigger, series=series, xAxis=xAxis, yAxis=yAxis)

# 初始化radar图
@app.route("/radar", methods=['POST','GET'])
def radar():
    if request.method == 'POST':
        session["title"] = request.form.get("radarTitle")
        session["radarSubtitle"] = request.form.get("radarSubtitle")
        session["radarRadius"] = request.form.get("radarRadius")
        session["radarAreaStyle"] = request.form.get("radarAreaStyle")
        return render_template("radarE.html", data=returnData())
    elif request.method == 'GET' and len(session) > 0 and len(session.get("tableName")) > 0:
        return render_template("radarE.html", data=returnData())
    else:
        return render_template("login.html", error="会话已失效")
# 返回radar图
@app.route('/viewRadar', methods=['POST'])
def viewRadar():
    if request.method == 'POST':
        data = request.form.get('data')
        if data != "" and len(data.split('\r\n')) >= 3:
            datalines = data.split('\r\n')
            legend = []
            maxList = []
            names = []
            indicator = []
            dataList = []
            result = []
            for index in range(len(datalines)):
                # 类目
                if index == 0 and datalines[index][:2] == '类目':
                    for item in str(datalines[index][3:]).split("\t"):
                        names.append(item)
                # 最大值
                if index == 1 and datalines[index][:3] == '最大值':
                    for item in str(datalines[index][4:]).split("\t"):
                        maxList.append(item)
                # 其他数据
                elif index >= 2:
                    rowList = str(datalines[index]).split("\t")
                    legend.append(rowList[0])
                    temp = []
                    for index in range(1, len(rowList)):
                        temp.append(rowList[index])
                    dataList.append(temp)
            for index in range(len(names)):
                indicator.append({'name': names[index], 'max': int(maxList[index])})
            for index in range(len(legend)):
                result.append({'name': legend[index], 'value': dataList[index]})
            title = session.get('title')
            subTitle = session.get('radarSubtitle')
            if session.get('radarRadius') == 'true':
                shape = "shape: 'circle',"
            else:
                shape = ""
            if session.get('radarAreaStyle') == 'true':
                areaStyle = "areaStyle: {normal: {}},"
            else:
                areaStyle = ""
            return render_template('radar.html', title=title, subTitle=subTitle, shape=shape, indicator=indicator, data=result, areaStyle=areaStyle,legend=legend)

# 初始化地图
@app.route("/china", methods=['POST','GET'])
def china():
    if request.method == 'POST':
        session["title"] = request.form.get("mapTitle")
        session["mapSubtitle"] = request.form.get("mapSubtitle")
        if len(request.form.get("mapMax")) > 0:
            session["mapMax"] = float(request.form.get("mapMax"))
        else:
            session["mapMax"] = 200000
        session["mapDw"] = request.form.get("mapDw")
        return render_template("mapE.html", data=returnData())
    elif request.method == 'GET' and len(session) > 0 and len(session.get("tableName")) > 0 and len(session.get("tableName")) > 0:
        return render_template("scatterE.html", data=returnData())
    else:
        return render_template("login.html", error="会话已失效")

# 返回中国地理图
@app.route("/viewMap", methods=['POST'])
def viewMap():
    if request.method == 'POST':
        data = request.form.get("data")
        if data != "":
            result = []
            datalines = data.split("\r\n")
            for row in datalines:
                result.append({'name': row.split('\t')[0], 'value': int(row.split('\t')[1])})

        return render_template("map.html", title=session.get('title'), subTitle=session.get('mapSubtitle'), mapMax=session.get('mapMax'), mapDw=session.get('mapDw'), data=result)

if __name__ == "__main__":
    app.run(port=8888, debug=True)